import React, { useState, useEffect } from 'react'
import { Table, Button, Modal, notification } from 'antd'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined, UploadOutlined } from '@ant-design/icons';
import axios from 'axios';
const { confirm } = Modal

export default function NewsDraft(props) {
  const [dataSource, setDataSource] = useState([]);

  const { usernmae } = JSON.parse(localStorage.getItem("token"))
  useEffect(() => {
    axios.get(`/news?auther=admin&auditState=0&_expand=category`).then(res => {
      const list = res.data
      setDataSource(list)
      // console.log(list);
    })
  }, [usernmae])

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'name',  // 可写可不写
      render: (id) => <b>{id}</b>
    },
    {
      title: '新闻标题',
      dataIndex: 'title',
      render: (title, Item) => {
        return <a href={`#/news-manage/preview/${Item.id}`}>{title}</a>
      }
    },
    {
      title: '作者',
      dataIndex: 'auther',
      render: (auther) => <div>{auther}</div>
    },
    {
      title: '新闻分类',
      dataIndex: 'category',
      render: (category) => {
        return category.title
      }
    },
    {
      title: '操作',
      render: (Item) => <div>
        <Button shape="circle" danger><DeleteOutlined onClick={() => confirmMethod(Item)} /></Button>
        <div style={{ display: "inline-block", padding: "4px" }}></div>
        <Button shape="circle" onClick={() => {
          props.history.push(`/news-manage/update/${Item.id}`)
        }}><EditOutlined /></Button>
        <div style={{ display: "inline-block", padding: "4px" }}></div>
        <Button shape="circle" type="primary" onClick={() => handleCheck(Item.id)}><UploadOutlined /></Button>
      </div>
    },
  ];


  const handleCheck = (id) => {
    axios.patch(`/new/${id}`, {
      auditState: 1
    }).then(res => {
      props.history.push('/audit-manage/list')
      notification.info({
        message: `通知`,
        description: `您可以到${'审核列表'}中查看你的新闻`,
        placement: 'bottomRight',
      });
    })
  }




  // 删除弹窗
  const confirmMethod = (Item) => {
    confirm({
      title: '你确定要删除吗？',
      icon: <ExclamationCircleOutlined />,
      onOk() {
        // console.log('确定');
        deleteMethod(Item)
      },
      onCancel() {
        // console.log('取消');
      },
    });
  }

  // 删除操作
  const deleteMethod = (Item) => {
    // console.log(Item);
    setDataSource(dataSource.filter(data => data.id !== Item.id))
    axios.delete(`/news/${Item.id}`)

  }

  return (
    <div>
      <Table
        columns={columns}
        dataSource={dataSource}
        pagination={{
          pageSize: 5
        }}
        rowKey={Item => Item.id}
      />
    </div>
  )
}
